package cz.movie.subRenamer.util;

import java.io.File;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

public class FileNameUtil {
	final static Set<String> archiveExtensions = new HashSet<String>();
	static {
		archiveExtensions.add("zip");
		archiveExtensions.add("jar");
		archiveExtensions.add("rar");
		archiveExtensions.add("7z");
	}

	public static String getExtension(String s) {
		String[] split = s.split(Pattern.quote("."));
		if (split.length < 2) {
			return "";
		}
		return split[split.length - 1];
	}

	public static boolean isArchiveFile(String s) {
		return archiveExtensions.contains(getExtension(s).toLowerCase());
	}

	public static File createTmpDir() {
		File baseDir = new File(System.getProperty("java.io.tmpdir"));
		return createTmpDir(baseDir);
	}

	public static File createTmpDir(File baseDir) {
		if (baseDir == null) {
			return createTmpDir();
		}
		String baseName = System.currentTimeMillis() + "-";
		for (int counter = 0; counter < Integer.MAX_VALUE; counter++) {
			File tempDir = new File(baseDir, baseName + counter);
			if (tempDir.mkdir()) {
				return tempDir;
			}
		}
		throw new IllegalStateException("Failed to create directory within " + Integer.MAX_VALUE + " attempts (tried " + baseName + "0 to " + baseName + (Integer.MAX_VALUE - 1) + ')');
	}

	public static List<File> getAllFilesForDir(File baseDir) {
		List<File> listFile = new LinkedList<File>();
		if (!baseDir.isDirectory()) {
			return listFile;
		}
		getAllFilesForDir(baseDir.listFiles(), listFile);
		return listFile;
	}

	private static void getAllFilesForDir(File[] listFiles, List<File> listFile) {
		for (File file : listFiles) {
			if (file.isFile()) {
				listFile.add(file);
			} else if (file.isDirectory()) {
				getAllFilesForDir(file.listFiles(), listFile);
			}
		}
	}

	public static String getNameWithnoutExtension(String name) {
		int lastIndexOfDot = name.lastIndexOf(".");
		if (name.length() > 1 && lastIndexOfDot > 0) {
			return name.substring(0, lastIndexOfDot);
		}
		throw new RuntimeException("possible mistake there is no string to separate extension");
	}

	public static String addZeroPrefix(int widht, String number) {
		while (number.length() < widht) {
			number = 0 + number;
		}
		return number;
	}

	public static void onEachFileDoStuff(File basedir, Action<File> action) {
		File[] listFiles = basedir.listFiles();
		for (File file : listFiles) {
			if (file.isDirectory()) { // check if directory must be first
				onEachFileDoStuff(file, action);
			}
			action.doStuff(file);
		}
	}

	public static void deleteAllEmptyFolders(File baseDir) {
		FileNameUtil.onEachFileDoStuff(baseDir, new Action<File>() {

			public void doStuff(File file) {
				if (file.isDirectory() && file.list().length == 0) {
					file.delete();
				}
			}
		});
	}
}
